package com.sky.controller.common;


import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

import static com.sky.constant.MessageConstant.UPLOAD_FAILED;

/**
 * 公共接口
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "公共接口")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        log.info("上传文件:{}", file);
        try {
            //1.使用aliossutil上传文件
            String filename = file.getOriginalFilename();//获取原始文件名 桌面背景.jpg
            //1.1截取文件名后缀
            String extension = filename.substring(filename.lastIndexOf("."));
            //1.2拼接新的文件名
            String newFileName = UUID.randomUUID()+extension;
            //2.上传文件
            String upload = aliOssUtil.upload(file.getBytes(), newFileName);
            return Result.success(upload);
        } catch (IOException e) {
            return Result.error(UPLOAD_FAILED);
        }
    }

}
